<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.currPage"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :change-page="changePage"
        :change-cell="changeCell"
        :editFunc="handleEdit"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd"
            >新增</el-button
          >
        </template>
        <!-- 状态 0-停用 1-启用 -->
        <template #configStatus="{ rows }">
          <el-popover
            effect="light"
            trigger="hover"
            placement="top"
            width="auto"
            v-if="!rows.configStatus"
          >
            <template #default>
              <div>可启用</div>
            </template>
            <template #reference>
              <el-tag type="danger">停用</el-tag>
            </template>
          </el-popover>
          <el-tag type="success" v-if="rows.configStatus">启用</el-tag>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="closeDialog"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
        @closeDialogP="closeDialog"
      >
      </TableEdit>
    </el-dialog>
    <el-dialog title="详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData" @closeDialogP="visible1 = false">
      </TableDetail>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { User } from "@/types/user";
import { SubscriptionConfig } from "@/types/subscriptionConfig";
import {
  fetchSubscriptionConfig,
  fetchSubscriptionCreate,
  fetchSubscriptionConfigDelete,
  fetchSubscriptionEnabledConfig,
} from "@/api/configuration";
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import { FormOption, FormOptionList } from "@/types/form-option";

// 查询相关
const query = reactive({
  keyword: "",
});
const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "版本名称：", prop: "keyword",placeholder:"请输入版本名称" },
]);
const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "monthlyPrice", label: "月付单价", width: 150 },
  { prop: "monthlyDailyLimit", label: "月付单日下载歌曲上限", width: 150 },
  { prop: "quarterlyPrice", label: "季付单价", width: 150 },
  { prop: "quarterlyDailyLimit", label: "季付单日下载歌曲上限", width: 150 },
  { prop: "yearlyPrice", label: "年付单价", width: 150 },
  { prop: "yearlyDailyLimit", label: "年付单日下载歌曲上限", width: 150 },
  { prop: "versionName", label: "版本名称", width: 150 },
  { prop: "versionDesc", label: "版本描述", width: 150 },
  { prop: "equityContent", label: "权益内容", width: 320 },
  { prop: "configStatus", label: "状态", width: 150 },
  { prop: "createTime", label: "创建时间" },
  { prop: "operator", label: "操作", width: 300, fixed: "right" },
]);
const page = reactive({
  currPage: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
const getData = async () => {
  let params = {
    currPage: page.currPage,
    size: page.size,
    keyword: query.keyword,
  };
  const res = await fetchSubscriptionConfig(params);
  console.log("获取订阅配置列表");

  let list = res.data.data.records;
  let obj = {};
  if (list.length > 0) {
    list.forEach((item) => {
      if (Array.isArray(item.equityContent)) {
        item.equityContent = item.equityContent.join(",");
      }
      console.log(item);
      console.log(item.equityContent);
    });
  }
  console.log(list);
  tableData.value = res.data.data.records;
  page.total = res.data.data.total;
  // console.log(page.total);
};
getData();

// 分页
const changePage = (val: number) => {
  console.log("点击分页");

  page.currPage = val;
  console.log(page.currPage);
  getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: "90px",
  span: 24,
  list: [
    { type: "input", label: "月付单价", prop: "monthlyPrice",placeholder:"请输入月付单价"},
    { type: "input", label: "月付单日下载歌曲上限", prop: "monthlyDailyLimit",placeholder:"请输入月付单日下载歌曲上限" },
    { type: "input", label: "季付单价", prop: "quarterlyPrice",placeholder:"请输入季付单价" },
    {
      type: "input",
      label: "季付单日下载歌曲上限",
      prop: "quarterlyDailyLimit",
      placeholder:"请输入季付单日下载歌曲上限"
    },
    { type: "input", label: "年付单价", prop: "yearlyPrice",placeholder:"请输入年付单价" },
    { type: "input", label: "年付单日下载歌曲上限", prop: "yearlyDailyLimit",placeholder:"请输入年付单日下载歌曲上限" },
    { type: "input", label: "版本名称", prop: "versionName",placeholder:"请输入版本名称" },
    { type: "input", label: "版本描述", prop: "versionDesc",placeholder:"请输入版本描述" },
    { type: "input", label: "权益描述", prop: "benefitsDesc",placeholder:"请输入权益描述" },
    { type: "input", label: "权益内容（用,隔开）", prop: "equityContent",placeholder:"请输入权益内容" },
    // {
    //   type: "switch",
    //   label: "状态",
    //   prop: "configStatus",
    //   activeValue: 1,
    //   inactiveValue: 0,
    //   activeText: "启用",
    //   inactiveText: "停用",
    // },
  ],
});
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});

// 新增
const handleAdd = (row) => {
  console.log("新增");
  rowData.value = { ...row };
  console.log(rowData.value);
  isEdit.value = false;
  visible.value = true;
};

// 编辑
const handleEdit = (row) => {
  console.log("编辑");
  rowData.value = { ...row };
  console.log(rowData.value);
  isEdit.value = true;
  visible.value = true;
};
const updateData = async (data) => {
  console.log("编辑或者新增");
  console.log(data);
  data.equityContent = data.equityContent.split(",");
  let datas = {};
  let obj = { subscriptionConfigId: data.subscriptionConfigId };
  if (isEdit.value) {
    datas = { ...obj, ...data };
  } else {
    datas = { ...data };
  }
  console.log(datas);
  const res = await fetchSubscriptionCreate(datas);
  console.log("创建/修改订阅配置");
  console.log(res.data);
  closeDialog();
  getData();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: [],
});
const handleView = (row: SubscriptionConfig) => {
  if (Array.isArray(row.equityContent)) {
    row.equityContent = row.equityContent.join(",");
  }

  viewData.value.row = { ...row };
  console.log("详情");
  console.log(viewData.value.row);
  console.log(row.equityContent);
  viewData.value.list = [
    {
      prop: "monthlyPrice",
      label: "月付单价",
    },
    {
      prop: "monthlyDailyLimit",
      label: "月付单日下载歌曲上限",
    },
    {
      prop: "quarterlyPrice",
      label: "季付单价",
    },
    {
      prop: "quarterlyDailyLimit",
      label: "季付单日下载歌曲上限",
    },
    {
      prop: "yearlyPrice",
      label: "年付单价",
    },
    {
      prop: "yearlyDailyLimit",
      label: "年付单日下载歌曲上限",
    },
    {
      prop: "versionName",
      label: "版本名称",
    },
    {
      prop: "versionDesc",
      label: "版本描述",
    },
    {
      prop: "benefitsDesc",
      label: "权益描述",
    },
    {
      prop: "equityContent",
      label: "权益内容",
    },
    {
      prop: "createTime",
      label: "创建时间",
    },
  ];
  visible1.value = true;
};

// 删除相关
const handleDelete = async (row) => {
  console.log("删除");
  console.log(row);
  let datas = {
    id: row.subscriptionConfigId,
  };
  const res = await fetchSubscriptionConfigDelete(datas);
  if (res.data.code == 0) {
    ElMessage.success("删除成功");
    getData();
  }
};

// 点击单元格
const changeCell = (val, column, rowIndex, columnIndex) => {
  console.log("点击单元格");
  // console.log(val);
  // console.log(column, rowIndex, columnIndex);
  if (column.label == "状态" && val.configStatus == 0) {
    let datas = {
      subscriptionConfigId: val.subscriptionConfigId,
    };
    ElMessageBox.confirm("确定要启用该订阅配置吗？", "提示", {
      type: "warning",
    })
      .then(async () => {
        const res = await fetchSubscriptionEnabledConfig(datas);
        if (res.data.code == 0) {
          ElMessage.success("启用成功");
          getData();
        }
      })
      .catch(() => {});
  }
};
</script>

<style scoped>
::v-deep .el-form-item__label {
  line-height: normal;
  align-items: center;
}
</style>
